import { ref } from 'vue';
import { httpType, httpData, unknownType } from './types';
import { hideLoading, showLoading, showToast } from './messageTip';
import { clearToken, getStorage } from './uni-storage';

/**
 * 未登录码
 */
const NOT_LOGIN_CODE = -997;

/**
 * 用来记录年检异常组件的ref
 * 在组件封装是已经引入挂载
 */
const yearlyErrorEmit = ref();

/**
 * 年检异常弹框挂载ref方法
 */
export function useYearlyErrorRequest(emit: unknownType) {
    yearlyErrorEmit.value = emit;
}

function http(data: httpData, method: httpType, url: string) {
    const token = getStorage('token');
    const baseUrl = getStorage('baseUrl') || (import.meta.env.VITE_API_URL as string);

    showLoading('请求中');

    return new Promise((resolve) => {
        uni.request({
            url: baseUrl + url,
            method,
            data,
            dataType: 'json',
            header: {
                'v-token': token,
            },
            timeout: 180000,
            success: (res) => {
                responseHandler(res, resolve);
            },
            fail: () => {
                handleError();
                hideLoading();
            },
            complete: () => {
                hideLoading();
            },
        });
    });
}

function responseHandler(res: httpData, resolve: httpData) {
    const { code } = res.data;
    if (code === NOT_LOGIN_CODE) {
        // 未登录处理
        clearToken();

        uni.showToast({
            title: '登录失效，请重新登录',
            icon: 'none',
            mask: true,
            complete: () => {
                uni.navigateTo({ url: '/pages/login/index' });
            },
        });

        return;
    }

    // 请求成功
    if (Math.floor(code / 100) === 1) {
        return resolve({ ...res.data });
    }

    // 请求错误或者异常
    if (Math.floor(code / 100) === 2 || Math.floor(code / 100) === 3) {
        httpToast(res.data?.message);
        return resolve(false);
    }
}

/**
 * 错误处理
 */
function handleError() {
    uni.showToast({
        title: '网络错误或服务器错误',
        icon: 'none',
        mask: false,
    });
}

/**
 * 消息提示
 * @param message 提示信息
 */
export function httpToast(message = '未知错误') {
    uni.showToast({
        title: message,
        icon: 'none',
        mask: false,
        duration: 1000 * 5,
    });
}

/**
 * get请求
 */
export function get(url: string, data?: httpData): Promise<any> {
    return http(data, 'GET', url);
}

/**
 * post请求
 */
export function post(url: string, data?: httpData): Promise<any> {
    return http(data, 'POST', url);
}
